#ifndef CLIENT_H
#define CLIENT_H

#include <wayland-client.h>
#include <iostream>
#include "xdg-shell-client-protocol.h"
class ClientState
{
private:
    static void static_configure(void *data, xdg_surface *surface, uint32_t serial)
    {
        static_cast<ClientState *>(data)->on_configure(surface, serial);
    }

    void on_configure(xdg_surface *surface, uint32_t serial)
    {
        xdg_surface_ack_configure(surface, serial); // 实际处理逻辑
    }

    static void wl_buffer_release(void *data, struct wl_buffer *wl_buffer)
    {
        // 原来实现：1.创建wl_buffer ->2.绘制渲染->3.destroy wl_buffer 下一帧重复该过程
        // 现在实现：双缓冲把wl_buffer缓存起来就不主动destroy wl_buffer，等到clientstate析构释放
        // wl_buffer_destroy(wl_buffer);
        //std::cout << " wl_buffer_release" << std::endl;
    }

    static void static_frame_handle_done(void *data, struct wl_callback *cb, uint32_t time)
    {
        static_cast<ClientState *>(data)->frame_handle_done(cb, time);
    }

    void frame_handle_done(struct wl_callback *cb, uint32_t time);

    static void
    xdg_wm_base_ping(void *data, struct xdg_wm_base *xdg_wm_base, uint32_t serial)
    {
        xdg_wm_base_pong(xdg_wm_base, serial);
    }
    static void static_registry_global(void *data, wl_registry *registry, uint32_t name,
                                       const char *interface, uint32_t version)
    {
        static_cast<ClientState *>(data)->registry_global(registry, name, interface, version);
    }
    void registry_global(struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version);

public:
    wl_buffer *buffers[2];           // 双缓冲区对象
    uint32_t *buffer_data[2];        // 缓冲区内存指针
    int current_buffer = 0;          // 当前使用的缓冲区索引
    bool buffer_initialized = false; // 缓冲区初始化标志
    wl_display *wl_display{nullptr};
    wl_registry *wl_registry{nullptr};
    wl_compositor *wl_compositor{nullptr};
    wl_surface *wl_surface{nullptr};
    xdg_wm_base *xdg_wm_base{nullptr};
    xdg_surface *xdg_surface{nullptr};
    xdg_toplevel *xdg_toplevel{nullptr};
    wl_shm *wl_shm{nullptr};
    xdg_surface_listener xdg_surface_listener;
    wl_buffer_listener wl_buffer_listener;
    wl_callback_listener frame_listener;
    xdg_wm_base_listener xdg_wm_base_listener;
    wl_registry_listener registry_listener;
    int anim_phase;
    ClientState();
    void init_buffers();
    void create_surface();
    void create_xdg_surface();
    void setup_frame_callback();
    void draw_frame(uint32_t *data);
    ~ClientState();
};
#endif // CLIENT_H